package cn.cellcom.agent.util;

import java.io.ByteArrayOutputStream;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

import cn.cellcom.agent.token.TokenEntity;

/**
 * 
 */
public class SerializableUtils {

	private static Kryo kryo;

	static {
		kryo = new Kryo();
		kryo.setReferences(false);
	}

	public static <T> void register(Class<T> t) {
		kryo.register(t);
	}

	public static <T> byte[] serialize(T relation) {
		byte[] bytes = null;
		ByteArrayOutputStream baos = null;
		Output output = null;
		try {
			baos = new ByteArrayOutputStream();
			output = new Output(baos);
			kryo.writeObjectOrNull(output, relation, relation.getClass());
			output.flush();
			bytes = baos.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (output != null) {
					output.close();
				}
				if (baos != null) {
					baos.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return bytes;
	}

	public static <T> T unserialize(byte[] bytes, Class<T> t) {
		T relation = null;
		Input input = null;
		try {
			input = new Input(bytes);
			relation = (T) kryo.readObject(input, t);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (input != null) {
				input.close();
			}
		}
		return relation;
	}

	public static void main(String[] args) {
		TokenEntity tk = new TokenEntity();
		tk.setToken("123456");		
		byte[] r = SerializableUtils.serialize(tk);
		System.out.println(r.length);
		TokenEntity tk2 = SerializableUtils.unserialize(r, TokenEntity.class);
		System.out.println(tk2.getToken());
	}
}
